package com.itheima.service.Impl;

import com.itheima.mapper.OrdersettingMapper;
import com.itheima.service.OrderService;
import com.itheima.service.OrdersettingService;
import io.swagger.v3.oas.models.responses.ApiResponse;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

@Service
public class OrdersettingServiceImpl implements OrdersettingService {
    @Autowired
    private OrdersettingMapper OrdersettingMapper;
    @Autowired
    private OrderService orderService;
    @Override
    public byte[] generateOrderSettingExcel() throws IOException {
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("订单设置");

            // 创建表头
            Row headerRow = sheet.createRow(0);
            CellStyle headerStyle = workbook.createCellStyle();
            Font font = workbook.createFont();
            font.setBold(true);
            headerStyle.setFont(font);

            String[] headers = {"ID", "日期", "最大预约数", "已预约数"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
            }

            // 示例行数据
            Row dataRow = sheet.createRow(1);
            dataRow.createCell(0).setCellValue(1);
            dataRow.createCell(1).setCellValue("2025-04-05");
            dataRow.createCell(2).setCellValue(100);
            dataRow.createCell(3).setCellValue(20);

            // 自动调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            workbook.write(byteArrayOutputStream);
            return byteArrayOutputStream.toByteArray();
        }
    }
    @Override
    public void handleFileUpload(MultipartFile excelFile) throws Exception {
        try (Workbook workbook = new XSSFWorkbook(excelFile.getInputStream())) {
            Sheet sheet = workbook.getSheetAt(0);
            if (sheet == null) {
                throw new IllegalArgumentException("Excel 文件内容为空");
            }

            // 处理 Excel 文件内容
            for (Row row : sheet) {
                if (row.getRowNum() == 0) {
                    // 跳过表头
                    continue;
                }

                // 读取行数据
                Cell idCell = row.getCell(0);
                Cell dateCell = row.getCell(1);
                Cell maxNumberCell = row.getCell(2);
                Cell reservedNumberCell = row.getCell(3);

                if (idCell != null && dateCell != null && maxNumberCell != null) {
                    int id = (int) idCell.getNumericCellValue();
                    String date = dateCell.getStringCellValue();
                    int maxNumber = (int) maxNumberCell.getNumericCellValue();
                    int reservedNumber = reservedNumberCell == null ? 0 : (int) reservedNumberCell.getNumericCellValue();

                    // 进行业务处理（例如保存到数据库）
                    System.out.println("ID: " + id + ", Date: " + date + ", Max Number: " + maxNumber + ", Reserved Number: " + reservedNumber);
                }
            }
        }

        // 获取 resources/templates 目录路径
        String templatesPath = URLDecoder.decode(getClass().getResource("/templates").getPath(), StandardCharsets.UTF_8.name());
        File uploadDir = new File(templatesPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 生成唯一文件名
        String fileName = generateUniqueFileName(excelFile.getOriginalFilename());
        File destFile = new File(uploadDir, fileName);

        try {
            excelFile.transferTo(destFile);
            System.out.println("文件已保存到: " + destFile.getAbsolutePath());
        } catch (Exception e) {
            throw new RuntimeException("文件保存失败", e);
        }
    }

    private String generateUniqueFileName(String originalFilename) {
        String[] parts = originalFilename.split("\\.");
        String extension = parts.length > 1 ? parts[parts.length - 1] : "xlsx";
        return System.currentTimeMillis() + "." + extension;
    }
    @Override
    public void editNumberByOrderDate(String number, String orderDate) {
        // 这里实现根据 orderDate 更新 number 的业务逻辑
        // 实际项目中应替换为具体的数据库操作
        OrdersettingMapper.updateNumberByOrderDate(orderDate, number);
        System.out.println("Updating order setting: Order Date=" + orderDate + ", Number=" + number);
    }
    @Override
    public ApiResponse getOrderSettingByMonth(String month) {
        // 这里实现根据 month 获取预约设置列表的业务逻辑
        // 获取指定月份的预约设置列表
        List<Map<String, Object>> orderSettingList = OrdersettingMapper.findByMonth(month);
        return new ApiResponse();
    }


}